package com.example.app1;

import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.PersistableBundle;

import android.view.View;
import android.os.Bundle;
import android.widget.Toast;

import com.example.app1.service.MyTextToSpeechService;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends FragmentActivity {

    private static final String TAG = "MainActivity";

    private ViewPager viewPager;
    private MyPagerAdapter pagerAdapter;
    private BroadcastReceiver receiver;
    private IntentFilter filter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.setLogDir(getExternalCacheDir().getAbsolutePath());

        LogUtil.info(TAG, "onCreate");

        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewPager);
        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        if (!isServiceRunning(MyTextToSpeechService.class)) {
            // 没有开启服务，跳转到配置界面
            viewPager.setCurrentItem(1, true);
        } else {
            this.restore();  // 从服务恢复数据
        }

        // 接收广播
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String callbackJson = intent.getStringExtra("data");
                try {
                    JSONObject callback = new JSONObject(callbackJson);
                    if (callback.has("type") && "toast".equals(callback.getString("type"))) {
                        // 发起通知
                        String message = callback.getString("msg");
                        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

                    } else if (callback.has("type") && "currentIdx".equals(callback.getString("type"))) {
                        // 更新当前播放片断标记
                        MainFragment mainFragment = (MainFragment) pagerAdapter.getItem(0);
                        mainFragment.setCurrentIdx(callback.getString("currentIdx"));

                    } else if (callback.has("type") && "changePauseButtonStatus".equals(callback.getString("type"))) {
                        boolean isShow = callback.getBoolean("isShow");
                        SettingsFragment settingsFragment = (SettingsFragment) pagerAdapter.getItem(1);
                        settingsFragment.changePauseButtonStatus(isShow);

                    } else {
                        MainFragment mainFragment = (MainFragment) pagerAdapter.getItem(0);
                        mainFragment.setResultText(callback.getString("content"));

                        SettingsFragment settingsFragment = (SettingsFragment) pagerAdapter.getItem(1);
                        String callBackId = callback.getString("id");
                        if (!"".equals(callBackId)) {
                            settingsFragment.setItemId(callBackId);
                        }
                    }

                } catch (JSONException e) {
                    LogUtil.info(TAG, "广播消息json格式错误->" + callbackJson, e);
                }
            }
        };
        filter = new IntentFilter("custom-action");
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.info(TAG, "onStart 启动前台服务");
        // 启动前台服务
        Intent serviceIntent = new Intent(getApplicationContext(), MyTextToSpeechService.class);
        // 启动服务
        startService(serviceIntent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.info(TAG, "onStop");
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.info(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.info(TAG, "onPause");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.info(TAG, "onReStart");
    }

    @Override
    public boolean onNavigateUp() {
        boolean b = super.onNavigateUp();
        LogUtil.info(TAG, "onNavigateUp");
        return b;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // 在 Activity 即将被销毁前调用，用于保存当前 Activity 的状态信息，以便在重建时恢复。
        super.onSaveInstanceState(outState);
        LogUtil.info(TAG, "onNavigateUp");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        // 在 Activity 即将被销毁前调用，用于保存当前 Activity 的状态信息，以便在重建时恢复。
        super.onSaveInstanceState(outState, outPersistentState);
        LogUtil.info(TAG, "onNavigateUp2");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
//        在 Activity 重建时调用，用于恢复之前保存的状态信息。
        LogUtil.info(TAG, "onRestoreInstanceState");
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onRestoreInstanceState(savedInstanceState, persistentState);
        // 在 Activity 重建时调用，用于恢复之前保存的状态信息。
        LogUtil.info(TAG, "onRestoreInstanceState");
    }

    // Override onBackPressed to handle back press event
    @Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() == 0) {
            super.onBackPressed();
        } else {
            viewPager.setCurrentItem(0, true);
        }
    }

    @Override
    protected void onDestroy() {
        LogUtil.info(TAG, "onDestroy");
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    public boolean isServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 按钮播放事件
     * @param view 页面view
     */
    public void play(View view) {
        SettingsFragment settingsFragment = (SettingsFragment) pagerAdapter.getItem(1);
        String id = settingsFragment.getItemId();
        String preUrl = settingsFragment.getPreUrl();

        if (isServiceRunning(MyTextToSpeechService.class)) {
            // 发送广播来调用service
            Intent intent = new Intent();
            intent.setAction("myhandle");
            intent.putExtra("command", "play");
            intent.putExtra("id", id);
            intent.putExtra("preUrl", preUrl);
            sendBroadcast(intent);
        } else {
            String params = "{\"preUrl\": \"" + preUrl + "\", \"id\": \"" + id + "\"}";

            // 创建Intent并将TextView的内容放入Extra中
            Intent serviceIntent = new Intent(view.getContext(), MyTextToSpeechService.class);
            serviceIntent.putExtra("params", params);

            // 启动服务
            startService(serviceIntent);
        }
        viewPager.setCurrentItem(0, true);  // 切换界面
    }

    public void pause(View view) {
        LogUtil.info(TAG, "touch pause");

        Intent intent = new Intent("myhandle");
        intent.putExtra("command", "pause");
        sendBroadcast(intent);  // 发送广播给界面

        LogUtil.info(TAG, "sendBroadcast myHandle pause");
    }

    public void stop(View view) {
        LogUtil.info(TAG, "touch stop");

        Intent intent = new Intent("myhandle");
        intent.putExtra("command", "stop");
        sendBroadcast(intent);  // 发送广播给界面

        LogUtil.info(TAG, "sendBroadcast myHandle stop");
    }

    public void next(View view) {
        LogUtil.info(TAG, "touch next");
        Intent intent = new Intent("myhandle");
        intent.putExtra("command", "next");
        sendBroadcast(intent);  // 发送广播给界面

        LogUtil.info(TAG, "sendBroadcast myHandle next");
        viewPager.setCurrentItem(0, true);  // 切换界面
    }

    public void previous(View view) {
        LogUtil.info(TAG, "touch previous");
        Intent intent = new Intent("myhandle");
        intent.putExtra("command", "previous");
        sendBroadcast(intent);  // 发送广播给界面

        LogUtil.info(TAG, "sendBroadcast myHandle previous");
        viewPager.setCurrentItem(0, true);  // 切换界面
    }

    private void restore() {
        // 恢复界面时请求服务，看有没有数据要恢复的
        // 如果是恢复app界面，需要请求服务更新界面
        Intent intent = new Intent();
        intent.setAction("myhandle");
        intent.putExtra("command", "restore");  // 界面恢复
        sendBroadcast(intent);
    }
}